console.log("千秋纪页面脚本已加载");

document.addEventListener('DOMContentLoaded', () => {
    // "千秋纪"页面的交互逻辑将在这里初始化
    setupTimelineScroll();
    renderTimelineEvents();
    renderBadges();
    const main = document.querySelector('main');
    if(main) main.classList.add('fade-page-enter');
});

function setupTimelineScroll() {
    const timeline = document.querySelector('.timeline-container');
    if (!timeline) return;

    timeline.addEventListener('wheel', (event) => {
        event.preventDefault();
        timeline.scrollLeft += event.deltaY;
    });
}

function renderTimelineEvents() {
    const scrollContainer = document.querySelector('.timeline-scroll');
    if (!scrollContainer) return;

    scrollContainer.innerHTML = ''; // Clear placeholder

    timelineData.events.forEach(event => {
        const eventElement = document.createElement('div');
        eventElement.className = 'timeline-event';

        const content = `
            <div class="event-date">${event.date}</div>
            <div class="event-milestone"></div>
            <div class="event-description">
                <h3>${event.title}</h3>
                <p>${event.description}</p>
            </div>
        `;
        eventElement.innerHTML = content;
        scrollContainer.appendChild(eventElement);
    });
}

// 博古架徽章数据（含开源文物/成就）
const badgeData = [
  { name: "项目能手", image: "assets/images/badge-tiger-tally.png", link: "https://baike.baidu.com/item/虎符" },
  { name: "代码工匠", image: "assets/images/badge-jade-cong.png", link: "https://baike.baidu.com/item/玉琮" },
  { name: "青铜鼎", image: "assets/images/bronze_ding.png", link: "https://baike.baidu.com/item/鼎" },
  { name: "编钟", image: "assets/images/bianzhong.png", link: "https://baike.baidu.com/item/编钟" },
  { name: "活字印刷", image: "assets/images/movable_type.png", link: "https://baike.baidu.com/item/活字印刷术" },
  { name: "四大发明", image: "assets/images/four_inventions.png", link: "https://baike.baidu.com/item/四大发明" }
];

function renderBadges() {
    const shelf = document.querySelector('.badge-shelf');
    if (!shelf) return;
    shelf.innerHTML = '';
    // 粒子底座
    const bg = document.createElement('div');
    bg.className = 'badge-shelf-bg';
    bg.innerHTML = "<canvas id='badgeParticles'></canvas>";
    shelf.appendChild(bg);
    // 徽章均分排列
    badgeData.forEach(badge => {
        const badgeElement = document.createElement('a');
        badgeElement.className = 'badge-item';
        badgeElement.href = badge.link;
        badgeElement.target = '_blank';
        badgeElement.rel = 'noopener noreferrer';
        badgeElement.innerHTML = `
            <img src="${badge.image}" alt="${badge.name} 徽章">
            <p>${badge.name}</p>
        `;
        shelf.appendChild(badgeElement);
    });
}

// 博古架科技感粒子动效
(function() {
  const canvas = document.getElementById('badgeParticles');
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  function resize() {
    const parent = canvas.parentElement;
    canvas.width = parent.offsetWidth;
    canvas.height = parent.offsetHeight;
  }
  resize();
  window.addEventListener('resize', resize);
  // 粒子参数
  const N = 32;
  const particles = Array.from({length: N}, () => ({
    x: Math.random()*canvas.width,
    y: Math.random()*canvas.height,
    r: 2.2+Math.random()*2.2,
    dx: -0.3+Math.random()*0.6,
    dy: -0.3+Math.random()*0.6,
    alpha: 0.18+Math.random()*0.22
  }));
  function draw() {
    ctx.clearRect(0,0,canvas.width,canvas.height);
    const isNight = document.body.classList.contains('night-mode');
    for (const p of particles) {
      ctx.save();
      ctx.beginPath();
      ctx.arc(p.x, p.y, p.r, 0, 2*Math.PI);
      ctx.fillStyle = isNight ? 'rgba(176,160,132,0.18)' : 'rgba(194,59,35,0.18)';
      ctx.shadowColor = isNight ? '#b0a084' : '#c23b23';
      ctx.shadowBlur = 12;
      ctx.globalAlpha = p.alpha * (isNight ? 1.5 : 1);
      ctx.fill();
      ctx.shadowBlur = 0;
      ctx.restore();
      p.x += p.dx;
      p.y += p.dy;
      if (p.x < 0 || p.x > canvas.width) p.dx *= -1;
      if (p.y < 0 || p.y > canvas.height) p.dy *= -1;
    }
  }
  function animate() {
    draw();
    requestAnimationFrame(animate);
  }
  animate();
  // 夜间模式切换时重绘
  const obs = new MutationObserver(draw);
  obs.observe(document.body, {attributes:true, attributeFilter:['class']});
})();

// 千秋纪文化彩蛋气泡
(function() {
  const mainTitle = document.querySelector('.section-title');
  if (!mainTitle) return;
  let bubble;
  function showEgg() {
    if (bubble) return;
    bubble = document.createElement('div');
    bubble.className = 'cultural-egg-bubble';
    bubble.innerHTML = '文物小知识：虎符，古代兵权信物，象征军权与信任。';
    mainTitle.parentElement.appendChild(bubble);
    setTimeout(()=>{bubble.style.opacity=1; bubble.style.pointerEvents='auto';}, 80);
    setTimeout(hideEgg, 4200);
  }
  function hideEgg() {
    if (bubble) {
      bubble.style.opacity = 0;
      setTimeout(()=>{if(bubble) {bubble.remove(); bubble=null;}}, 400);
    }
  }
  mainTitle.addEventListener('mouseenter', showEgg);
  mainTitle.addEventListener('mouseleave', hideEgg);
  setTimeout(showEgg, 1200);
})();

// 未来任务:
// 1. 实现更平滑的滚动动画
// 2. 从后端API加载时间轴事件和徽章
// 3. 为事件点添加点击交互（例如，弹出模态框）
// 4. 动态生成时间轴事件和徽章
// 5. 优化滚动逻辑
// 6. 添加更多交互功能
// 7. 确保代码的可读性和可维护性
// 8. 考虑性能优化和错误处理
// 9. 实现时间轴的交互功能（例如，点击事件查看详细信息）
// 10. 添加时间轴的交互功能（例如，拖动时间轴） 